package org.adit.spring.hibernate.dao;

import java.util.List;

import org.adit.spring.hibernate.entity.Route;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import br.com.caelum.vraptor.ioc.Component;

@Component
public class RouteDao {

	private final Session session;

	public RouteDao(Session session) {
		this.session = session;
	}

	public Long salva(Route route) {
		Transaction tx = session.beginTransaction();
		Long id = (Long) session.save(route);
		tx.commit();
		return id;
	}

	@SuppressWarnings("unchecked")
	public List<Route> listaTudo() {
		return this.session.createCriteria(Route.class).list();
	}

	public Route carrega(Long id) {
		return (Route) this.session.load(Route.class, id);
	}

	public void atualiza(Route route) {
		Transaction tx = session.beginTransaction();
		session.update(route);
		tx.commit();
	}

	public void remove(Route route) {
		Transaction tx = session.beginTransaction();
		this.session.delete(route);
		tx.commit();
	}

	@SuppressWarnings("unchecked")
	public Route busca(Long id) {
		return (Route) this.session.load(Route.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<Route> buscaLista(String id) {
		return session.createCriteria(Route.class).add(Restrictions.ilike("id", id, MatchMode.ANYWHERE)).list();
	}

	public void recarrega(Route route) {
		session.refresh(route);
	}
}